<?php

namespace app\http\middleware;
use think\helper\Time;
use think\Db;
use think\facade\Request;
class Check
{
    public function handle($request, \Closure $next)
    {
		$file=env('root_path').'tpl/'.'install.txt';
		if(!file_exists($file)){
		    file_put_contents($file,'install'); 
		}
		if(file_get_contents($file)=='install' and request()->controller()!="Install"){
			$file=env('root_path').'public/'.'.htaccess';
			file_put_contents($file,'<IfModule mod_rewrite.c>
  Options +FollowSymlinks -Multiviews
  RewriteEngine On

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?/$1 [QSA,PT,L]
</IfModule>'); 
			return redirect('/install/index.html');
		}else{
		    if(request()->controller()!="Install"){
                //这里记录所有的访问数据
                list($start, $end) = Time::today();
                if($b=Db::name('statistics')->where('time','>=',$start)->where('time','<',$end)->find()){
                    Db::name('statistics')->where('id',$b['id'])->setInc('pv');
                    if(Db::name('statistics_show')->where('ip',Request::ip())->find()){
                        if(!Db::name('statistics_show')->where('time','>=',$start)->where('time','<',$end)->where('ip',Request::ip())->find()){
                            Db::name('statistics')->where('id',$b['id'])->setInc('uv');
                        }
                    }else{
                        Db::name('statistics')->where('id',$b['id'])->setInc('ip');
                    }
                }else{
                    $id=Db::name('statistics')->insertGetId([
                        'time'=>time(),
                        'ip'=>0,
                        'pv'=>1,
                        'uv'=>1
                    ]);
                    if(!Db::name('statistics_show')->where('ip',Request::ip())->find()){
                        Db::name('statistics')->where('id',$id)->setInc('ip');
                    }
                }
                $a=[
                    'time'=>time(),
                    'ip'=>Request::ip(),
                    'url'=>Request::url(true),
                    'data'=>json_encode(input('param.')),
                    'method'=>Request::method(),
                    'controller'=>Request::controller(),
                    'module'=>Request::module(),
                    'action'=>Request::action(),
                    'file'=>!Request::file() ? 0 : sizeof(Request::file())
                ];
                Db::name('statistics_show')->insert($a);
            }
        }
	   if(request()->controller()!=="Notify" and request()->controller()!=="Install"){ //这个是微信支付的回调，以后回调都写在这个控制器里面的了
			$system= Db::name('system')->column('value','enname');
		   if($system["value"] != "开启"){
		       if($system["redirect"]){
		           return redirect($system["redirect"], '',302);
		       }
		       return json(['非法访问'])->code(404);
		       exit('网站关闭');
		   }
	   }
       return $next($request);
    }
}
